(function() {
    'use strict';

    /**
     * @ngdoc service
     * @name webApp.myrest
     * @description
     * # myrest
     * Service in the webApp.
     **/
    angular.module('webApp')
        .service('dataService', ['$rootScope', '$http', '$q', 'cacheService', 'sessionService', 'authService', 'ERP_CONFIG', 'md5', 'moment', '$filter', 'helper',
            function($rootScope, $http, $q, cacheService, sessionService, authService, ERP_CONFIG, md5, moment, $filter, helper) {
                var dataService = {
                    reject: reject,
                    promise: promise,
                    resolve: resolve,
                    userCurrentGet: userCurrentGet,
                    login: login,
                    logout: logout,
                    removeAllCache: removeAllCache,
                    removeDataCache: removeDataCache,
                    tpl: tpl,
                    getToken: getToken,
                    userGet: userGet,
                    userOne: userOne,
                    shopUserCurrentGet: shopUserCurrentGet,
                    /**********郭 start************/

                    /**********郭 end  ***********/
                    /**********朱旭 start*********/
                    areaGet: areaGet,
                    storeGet: storeGet,
                    storeOne: storeOne,
                    itemGet: itemGet,
                    itemOne: itemOne,
                    buyerRegister: buyerRegister,
                    buyerUpdatePw: buyerUpdatePw,
                    category: category,
                    favoritesGet: favoritesGet,
                    favoritesAdd: favoritesAdd,
                    favoritesDelete: favoritesDelete,
                    addressAdd: addressAdd,
                    addressGet: addressGet,
                    addressUpdate: addressUpdate,
                    addressDelete: addressDelete,
                    cartAdd: cartAdd,
                    cartGet: cartGet,
                    cartOne: cartOne,
                    cartupdatenum: cartupdatenum,
                    cartDelete: cartDelete,
                    buystep1: buystep1,
                    buystep2: buystep2,
                    paymentList: paymentList,
                    paymentAdd: paymentAdd,
                    orderGet: orderGet,
                    orderOne: orderOne,
                    orderStatusUpdate: orderStatusUpdate,
                    deliverGet: deliverGet,
                    reviewAdd: reviewAdd,
                    reviewGet: reviewGet,
                    wxaccess_token: wxaccess_token,
                    jssdk_wx: jssdk_wx,
                    /**********朱旭 end  *********/
                }
                return dataService;

                //清空所有缓存
                function removeAllCache() {
                    cacheService.destroy();
                    sessionService.removeAll();
                    return resolve();
                }

                //清空API请求缓存
                function removeDataCache() {
                    cacheService.destroy();
                    return resolve();
                }

                //获取用户登录信息
                function userCurrentGet(getCache) {
                    if (getCache) {
                        // var cacheInfo = sessionService.get('currentUserInfo');
                        var cacheInfo = cacheService.get("currentUserInfo")
                        if (cacheInfo) {
                            return resolve(cacheInfo);
                        }
                    }

                    var userType = sessionService.get("tokenUser")["userType"];
                    if (userType == 1) {
                        var mm = shopUserCurrentGet;
                    } else {
                        var mm = shopUserCurrentGet;
                    }
                    return mm().then(function(result) {
                        if (result) {
                            cacheService.set('currentUserInfo', result);
                            return result;
                        }
                    });
                }

                //退出
                function logout() {
                    return requestApi("/rest/buyer/user/logout").then(function(result) {
                        // sessionService.removeAll();
                        cacheService.destroy();
                        return result;
                    });
                }

                //登录动作
                function login(name, pwd) {
                    return requestApi("/public/buyer/login", {
                        user_name: name,
                        password: pwd
                    }).then(function(result) {
                        return result;
                    });
                }
                //行政区查询
                function areaGet(data) {

                    var xdata = clone(data);
                    xdata.order_by = "area:asc";
                    var ttl = 3 * 60 * 60;
                    return requestApi("/public/area/get", xdata, ttl).then(function(result) {
                        return result;
                    });
                }
                //店铺查询
                function storeGet(data) {

                    return requestApi("/public/store/get", data).then(function(result) {
                        return result;
                    });
                }

                function storeOne(partner_id) {
                    return storeGet({
                        query: {
                            "partner_id": partner_id
                        }
                    }).then(function(result) {
                        return result;
                    });
                }

                function itemGet(data) {
                    var xdata = data || {};
                    if (data.query) {
                        data.query["status_id"] = 1;
                    }
                    return requestApi("/public/item/get", xdata).then(function(result) {
                        return result;
                    });
                }

                function itemOne(item_id) {
                    return itemGet({
                        query: {
                            "item_id": item_id
                        }
                    }).then(function(result) {
                        if (result.Msg) {
                            return result;
                        } else {
                            return result.items[0];
                        }
                    });
                }
                //加载模板
                function tpl(url) {
                    return $http.get(url).then(function(result) {
                        //return 
                        if (result && result.data) {
                            return result.data;
                        } else {
                            return 'none template';
                        }
                    });
                }

                //用户列表
                function userGet(data, ttl) {
                    ttl = _.isNumber(ttl) ? ttl : 10 * 60
                    data.order_by = "created_at:desc";
                    return requestApi("/rest/user/get", data, ttl).then(function(result) {
                        return result;
                    });
                }

                //获取1个用户
                function userOne(user_id) {
                    if (!user_id) {
                        return reject("user_id为空");
                    }

                    var cache = oneCacheGet("userOne", user_id);
                    if (cache !== false) {
                        return cache;
                    }

                    return userGet({
                        query: {
                            "user_id": user_id
                        }
                    }).then(function(result) {
                        if (result.total_count == 1) {
                            return oneCacheSet("userOne", user_id, result.users[0]);
                        } else {
                            return reject("未找到id：" + user_id + "的数据");
                        }
                    });
                }

                function getToken(cb) {
                    // var token = sessionService.get('token');
                    var token = cacheService.get('token');
                    if (token) {
                        cb(token);
                    } else {
                        console.log("缺少token，需要登录！");
                        $rootScope.login();
                    }
                }
                //会员注册
                function buyerRegister(data) {
                    return requestApi("/public/buyer/register", data).then(function(result) {
                        return result;
                    });
                }
                //会员密码修改
                function buyerUpdatePw(data) {
                    var xdata = clone(data);
                    return requestApi("/rest/buyer/user/password/update", xdata).then(function(result) {
                        return result;
                    });
                }

                function shopUserCurrentGet() {
                    return requestApi("/rest/buyer/user/get").then(function(result) {
                        return result;
                    });
                }
                //商品分类
                function category() {
                    return requestApi("/public/category/get").then(function(result) {
                        return result;
                    });
                }

                function favoritesGet() {
                    return requestApi("/rest/buyer/favorites/get").then(function(result) {
                        return result;
                    });
                }
                //收藏添加
                function favoritesAdd(data) {
                    var xdata = clone(data);
                    return requestApi("/rest/buyer/favorites/add", xdata).then(function(result) {
                        return result;
                    });
                }

                function favoritesDelete(fav_id) {
                    return requestApi("/rest/buyer/favorites/delete", {
                        fav_id: fav_id
                    }).then(function(result) {
                        return result;
                    });
                }
                //地址添加
                function addressAdd(data) {
                    var xdata = clone(data);
                    return requestApi("/rest/buyer/address/add", xdata).then(function(result) {
                        return result;
                    });
                }
                //查询地址
                function addressGet() {
                    return requestApi("/rest/buyer/address/get").then(function(result) {
                        return result;
                    });
                }
                //地址删除
                function addressDelete(address_id) {
                    return requestApi("/rest/buyer/address/delete", {
                        address_id: address_id
                    }).then(function(result) {
                        return result;
                    });
                }

                function addressUpdate(data) {
                    var xdata = clone(data);
                    return requestApi("/rest/buyer/address/update", xdata).then(function(result) {
                        return result;
                    });
                }

                function cartAdd(data) {
                    var xdata = clone(data);
                    return requestApi("/rest/buyer/cart/add", xdata).then(function(result) {
                        return result;
                    });
                }

                function cartGet(data) {
                    return requestApi("/rest/buyer/cart/get", data).then(function(result) {
                        return result;
                    });
                }

                function cartOne(cart_id, buyer_id) {
                    var query;
                    if (cart_id) {
                        query = {
                            cart_id: cart_id
                        }
                    }
                    if (buyer_id) {
                        query = {
                            buyer_id: buyer_id
                        };
                    }
                    return cartGet().then(function(result) {
                        return result;
                    });
                }

                function cartupdatenum(data) {
                    var xdata = clone(data);
                    return requestApi("/rest/buyer/cart/quantity/update", xdata).then(function(result) {
                        return result;
                    });
                }
                //删除购物车
                function cartDelete(cart_id) {
                    return requestApi("/rest/buyer/cart/delete", {
                        cart_item_id: cart_id
                    }).then(function(result) {
                        return result;
                    });
                }
                //购买第一步
                function buystep1(data) {
                    var xdata = clone(data);
                    xdata.buy_para = angular.toJson(xdata.buy_para);
                    return requestApi("/rest/buyer/order/preview/add", xdata).then(function(result) {
                        return result;
                    });
                }
                //购买第二步
                function buystep2(data) {
                    var xdata = clone(data);
                    xdata.buy_para = angular.toJson(xdata.buy_para);
                    return requestApi("/rest/buyer/order/confirm/add", xdata).then(function(result) {
                        return result;
                    });
                }

                function paymentList() {
                    return requestApi("/rest/buyer/pay/type/get").then(function(result) {
                        return result;
                    });
                }

                function paymentAdd(data) {
                    var xdata = clone(data);
                    return requestApi("/rest/buyer/pay/add", xdata).then(function(result) {
                        return result;
                    });
                }
                //订单查询
                function orderGet(data) {
                    data.order_by = "created_at:desc";
                    // return   $http.post(ERP_CONFIG.eprUrl +"/rest/buyer/order/get",data)
                    //       .success(function(result){
                    //                 deferred.resolve(result);
                    //                 console.log(result);
                    //       })
                    //       .error(function(result){
                    //         deferred.reject(result);
                    //       });
                    return requestApi("/rest/buyer/order/get", data).then(function(result) {
                        return result;
                    });
                }

                function orderOne(order_id) {
                    return orderGet({
                        query: {
                            "order_id": order_id
                        }
                    }).then(function(result) {
                        if (result.Msg) {
                            return result;
                        } else {
                            return result.orders[0];
                        }
                    });
                }

                function orderStatusUpdate(order_id, event) {
                    var events = {
                        1: "E_ORDER_CANCEL", //取消订单
                        2: "E_ORDER_RECEIVE", //确认收货
                    }
                    event = events[event] || event;
                    var data = {
                        order_id: order_id,
                        event: event
                    };

                    return requestApi("/rest/buyer/order/status/update", data).then(function(result) {
                        return result;
                    });
                }
                //物流查询
                function deliverGet(data) {
                    return requestApi("/rest/buyer/logistics/get", data).then(function(result) {
                        return result;
                    });
                }
                ///rest/buyer/buy/review/add
                function reviewAdd(data) {
                    var xdata = clone(data);
                    return requestApi("/rest/buyer/review/add", xdata).then(function(result) {
                        return result;
                    });
                }

                function reviewGet(data) {
                    return requestApi("/public/review/get", data).then(function(result) {
                        return result;
                    });
                }

                function wxaccess_token(data) {
                    return requestApi("/public/buyer/wxlogin", data).then(function(result) {
                        return result;
                    });
                }

                function jssdk_wx(data) {
                    return requestApi("/rest/wechat/jssdk/get", data).then(function(result) {
                        return result;
                    });
                }
                //通用请求
                function requestApi(method, data, ttl) {
                    //开发模式下，ttl设置为0
                    // ttl = 0;
                    //console.log("api请求1：", ERP_CONFIG.eprUrl + method, data, JSON.stringify(data));
                    data = data ? data : {};


                    if (method.indexOf("/rest/buyer/") !== -1 || method.indexOf("/rest/wechat") !== -1) {
                        // data.token = sessionService.get('token');
                        data.token = cacheService.get('token');
                    }
                    if ("page_size" in data) {
                        if (!_.isNumber(data.page_size)) {
                            data.page_size = 10;
                        }
                    }

                    if ("page_no" in data) {
                        if (!_.isNumber(data.page_no)) {
                            data.page_no = 1;
                        }
                    }
                    //缓存
                    if (ttl) {
                        var questKey = md5.createHash(method + angular.toJson(data));
                        var cacheVal = cacheService.get(questKey, ttl);
                        if (cacheVal) {
                            // console.log("api命中缓存：", questKey, method, data, cacheVal);
                            return returnData(cacheVal);
                        } else {
                            //console.log("没有查到缓存：", cacheVal);
                        }
                    }

                    //组装query字段
                    if (data.query && !_.isObject(data.query)) {
                        return helper.message("query不是object：" + data.query, "error", 15);
                    }

                    if (data.query && _.isObject(data.query)) {
                        var queryTmp = [];
                        _.map(data.query, function(v, k) {
                            queryTmp.push(k + ":" + v);
                        });
                        data.query = queryTmp.join(",");
                    }
                    return $http.post(ERP_CONFIG.eprUrl + method, data).then(function(res) {
                        var result = clone(res.data);
                        if (ttl) {
                            // console.log("存入缓存：", method, questKey, data, result);
                            if (result && !result.Err) {
                                cacheService.set(questKey, result, ttl);
                            }
                        }
                        console.log("api请求2：", ERP_CONFIG.eprUrl + method, data, "返回：", JSON.parse(JSON.stringify(result)));
                        return returnData(result);
                    }, function(response) {
                        // console.log("http error:", response);

                        if (response.status == 510) {
                            if (method.indexOf("/add") != -1 || method.indexOf("/update") != -1 || method.indexOf("/delete") != -1) {
                                helper.message("缺少权限：" + method, "error", 15);
                            }
                            return {
                                Err: 1,
                                Msg: "Need permission:" + method
                            };
                        } else {
                            console.log("http error:", response);
                            return {
                                Err: 1,
                                Msg: "error...."
                            };
                        }
                    });
                }

                //总返回数据
                function returnData(data) {
                    var timeKeys = ['created_at', 'update_at', 'pre_in_time', 'produce_time', 'expire_time', 'pay_time'];
                    if (_.isArray(data) || _.isObject(data)) {
                        _.map(data, function(v, k) {
                            if (_.isString(v) && timeKeys.indexOf(k) != -1) {
                                data[k] = currentTime(v);
                            }

                            if (_.isArray(v) || _.isObject(v)) {
                                _.map(v, function(v1, k1) {
                                    if (_.isString(v1) && timeKeys.indexOf(k1) != -1) {
                                        data[k][k1] = currentTime(v1);
                                    }

                                    if (_.isArray(v1) || _.isObject(v1)) {
                                        _.map(v1, function(v2, k2) {
                                            if (_.isString(v2) && timeKeys.indexOf(k2) != -1) {
                                                data[k][k1][k2] = currentTime(v2);
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                    return resolve(data);
                }

                //把标准时间变成当地时间
                function currentTime(utcTime) {
                    return moment.tz(utcTime, "Etc/UTC").tz(moment.tz.guess()).format("YYYY-MM-DD HH:mm:ss");
                }

                //把当地变成标准时间
                function toStdTime(x) {
                    return $filter('stdTime')(x);
                }

                //返回promis
                function resolve(res) {
                    // console.log("resolve:", res);
                    var def = $q.defer();
                    def.resolve(res);
                    return def.promise;
                }

                function reject(res) {
                    return $q.reject(res);
                }

                function promise() {
                    return $q.when(true);
                }

            }
        ]);
})();
